<template>
  <div class="order-container">
    <el-row justify="center" :gutter="30">
      <!-- 左侧主要内容 -->
      <el-col :xs="24" :lg="16">
        <!-- 收货地址 -->
        <el-card class="address-box">
          <template #header>
            <div class="card-header">
              <span>收货地址</span>
              <div>
                <el-button type="primary" size="small" @click="handleAddAddress"
                  >新增地址</el-button
                >
                <el-button size="small" @click="handleEditAddress"
                  >编辑地址</el-button
                >
              </div>
            </div>
          </template>

          <el-radio-group v-model="selectedAddress">
            <el-row :gutter="20">
              <el-col
                v-for="(item, index) in addresses"
                :key="index"
                :span="24"
                class="address-item"
              >
                <el-radio :label="index" border>
                  <div class="address-content">
                    <div class="receiver">{{ item.receiver }}</div>
                    <div class="phone">{{ item.phone }}</div>
                    <div class="detail">{{ item.detail }}</div>
                  </div>
                </el-radio>
              </el-col>
            </el-row>
          </el-radio-group>
        </el-card>

        <!-- 商品信息 -->
        <el-card class="goods-box">
          <div class="goods-item" v-for="item in goods" :key="item.id">
            <el-image class="goods-img" :src="item.img"></el-image>
            <div class="goods-info">
              <div class="name">{{ item.name }}</div>
              <div class="price">¥{{ item.price }}</div>
              <el-input-number
                v-model="item.quantity"
                :min="1"
                size="small"
                controls-position="right"
              />
            </div>
          </div>

          <el-divider />

          <!-- 订单备注 -->
          <div class="order-remark">
            <span>订单备注：</span>
            <el-input
              v-model="remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
            />
          </div>

          <!-- 运费险 -->
          <div class="shipping-insurance">
            <el-checkbox v-model="insurance">运费险（¥5.00）</el-checkbox>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧提交订单 -->
      <el-col :xs="24" :lg="8">
        <el-card class="submit-box">
          <div class="price-summary">
            <div class="item">
              <span>商品总价：</span>
              <span>¥{{ totalPrice }}</span>
            </div>
            <div class="item">
              <span>运费：</span>
              <span>¥{{ shippingFee }}</span>
            </div>
            <div class="item total">
              <span>应付总额：</span>
              <span class="price">¥{{ totalPayment }}</span>
            </div>
          </div>
          <el-button
            type="primary"
            size="large"
            class="submit-btn"
            @click="handleSubmit"
          >
            提交订单
          </el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 地址管理弹窗 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="isEditing ? '编辑地址' : '新增地址'"
      width="600px"
    >
      <el-form
        ref="addressForm"
        :model="currentAddress"
        :rules="addressRules"
        label-width="80px"
      >
        <el-form-item label="收件人" prop="receiver">
          <el-input
            v-model="currentAddress.receiver"
            placeholder="请输入收件人姓名"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="currentAddress.phone"
            placeholder="请输入联系电话"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="currentAddress.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";

// 收货地址数据
const addresses = ref([
  {
    receiver: "张三",
    phone: "13800138000",
    detail: "北京市海淀区中关村大街1号",
  },
  {
    receiver: "李四",
    phone: "13900139000",
    detail: "上海市浦东新区陆家嘴金融中心",
  },
]);
const selectedAddress = ref(0);

// 商品数据
const goods = ref([
  {
    id: 1,
    img: "https://via.placeholder.com/80",
    name: "商品名称1",
    price: 199.0,
    quantity: 2,
  },
  {
    id: 2,
    img: "https://via.placeholder.com/80",
    name: "商品名称2",
    price: 299.0,
    quantity: 1,
  },
]);

// 其他数据
const remark = ref("");
const insurance = ref(true);
const shippingFee = ref(15.0);

// 地址弹窗相关逻辑
const addressDialogVisible = ref(false);
const isEditing = ref(false);
const editingIndex = ref(-1);

const currentAddress = reactive({
  receiver: "",
  phone: "",
  detail: "",
});

const addressForm = ref<FormInstance>();

const addressRules = reactive<FormRules>({
  receiver: [{ required: true, message: "请输入收件人姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  detail: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
});

// 计算属性
const totalPrice = computed(() => {
  return goods.value.reduce((sum, item) => sum + item.price * item.quantity, 0);
});

const totalPayment = computed(() => {
  return totalPrice.value + shippingFee.value + (insurance.value ? 5 : 0);
});

// 操作方法
const handleAddAddress = () => {
  isEditing.value = false;
  editingIndex.value = -1;
  resetAddressForm();
  addressDialogVisible.value = true;
};

const handleEditAddress = () => {
  if (selectedAddress.value === null) return;
  isEditing.value = true;
  editingIndex.value = selectedAddress.value;
  Object.assign(currentAddress, addresses.value[selectedAddress.value]);
  addressDialogVisible.value = true;
};

const saveAddress = async () => {
  const valid = await addressForm.value?.validate();
  if (!valid) return;

  if (isEditing.value) {
    addresses.value[editingIndex.value] = { ...currentAddress };
  } else {
    addresses.value.push({ ...currentAddress });
    selectedAddress.value = addresses.value.length - 1;
  }

  addressDialogVisible.value = false;
  resetAddressForm();
};

const resetAddressForm = () => {
  currentAddress.receiver = "";
  currentAddress.phone = "";
  currentAddress.detail = "";
  addressForm.value?.resetFields();
};

const handleSubmit = () => console.log("提交订单");
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 地址盒子 */
.address-box {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .address-item {
    margin-bottom: 20px;

    :deep(.el-radio) {
      width: 100%;
      padding: 15px;
      align-items: flex-start;
      /* 顶部对齐 */
    }

    .address-content {
      line-height: 1.8;
      /* 增加行高 */
      padding-left: 8px;

      .receiver {
        font-weight: bold;
        margin-bottom: 4px;
        /* 增加元素间距 */
      }

      .phone {
        color: #666;
        margin-bottom: 4px;
        /* 增加元素间距 */
      }

      .detail {
        color: #999;
        line-height: 1.6;
        word-break: break-all;
        /* 防止长地址溢出 */
      }
    }
  }
}

/* 商品信息 */
.goods-box {
  .goods-item {
    display: flex;
    margin-bottom: 20px;

    .goods-img {
      width: 80px;
      height: 80px;
      margin-right: 15px;
      border-radius: 4px;
    }

    .goods-info {
      flex: 1;

      .name {
        margin-bottom: 8px;
        font-weight: bold;
      }

      .price {
        color: #f56c6c;
        margin-bottom: 10px;
      }
    }
  }

  .order-remark {
    margin: 20px 0;
  }

  .shipping-insurance {
    margin-top: 15px;
  }
}

/* 提交盒子 */
.submit-box {
  .price-summary {
    .item {
      display: flex;
      justify-content: space-between;
      margin: 12px 0;
      color: #606266;

      &.total {
        font-size: 16px;

        .price {
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
  }

  .submit-btn {
    width: 100%;
    margin-top: 20px;
    padding: 20px 0;
    font-size: 16px;
  }
}

/* 弹窗样式 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea :deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 100px;
}

@media (max-width: 992px) {
  .submit-box {
    margin-top: 20px;
  }
}
</style>
